package eyrolles;

import eyrolles.modele.ModeleAccesIndisponibleException;
import eyrolles.modele.ModeleInterface;
import eyrolles.modele.ModeleUnknownUserException;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionMessage;


public class LoginAction extends GenericAction {


    
    
    public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {
        ModeleInterface mI = getModele();
        String user = null;

        // Cible par defaut en cas de succes
        String target = new String("success");

        // Utilisation de LoginForm pour obtenir les parametres
        // de la requete
        String username = ((LoginForm) form).getUsername();
        String password = ((LoginForm) form).getPassword();
        try {
            user = mI.getUser(username, password);

            // Cible en cas d'echec


            HttpSession session = request.getSession();
            session.setAttribute("USER", user);
        } catch (ModeleUnknownUserException e) {
            target = new String("login");
            ActionMessages errors = new ActionMessages();

            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("errors.login.unknown", username));


            // Enregistrer les erreurs  trouvees dans le formulaire original
            if (!errors.isEmpty()) {

                saveErrors(request, errors);
            }
        } catch (ModeleAccesIndisponibleException e) {

            target = new String("login");
            ActionMessages errors = new ActionMessages();

            errors.add(ActionMessages.GLOBAL_MESSAGE,
                    new ActionMessage("errors.database.error",
                    e.getMessage()));

            // Signaler les erreurs eventuelles
            if (!errors.isEmpty()) {

                saveErrors(request, errors);
            }
        } 
        // Transmission de la requete a la vue appropriee
        return (mapping.findForward(target));
    }
}
